<?php
namespace app\sub\controller;

use PHPQRCode\QRcode;
use think\facade\Config;
use think\Db;

class Aucing extends \Common {

    private $spec = ["size" => "规格"];

    # 设置商品状态
    public function SetGoodsState(){
        if(isset($_POST["lot_id"]) && isset($_POST["id"]) && isset($_POST["op"])){
            # state 0 未拍 1 正在拍 2 停拍（成交或流拍）
            $lid = $_POST["lot_id"];
            $gid = $_POST["id"];
            $op = $_POST["op"];

            # 上一件操作的商品
            $upGood = Db::name("goods")
                ->where("lid", $lid)
                ->order("clinch_time desc")
                ->find();

            # 现在正在进行的拍品
            $nowGood = Db::name("goods")
                ->where("lid", $_POST["lot_id"])
                ->where("state", 1)
                ->find();

            if((!empty($nowGood) && $gid == $nowGood["gid"]) || (!empty($upGood) && $gid == $upGood["gid"])){
                $msg = "抱歉，本件重新竞拍，开始出价！";
            }else{
                $msg = "开始出价！";
            }

            $good1 = Db::name("goods")->where("gid", $gid)->find();
            # start: 开始竞拍  cancel: 撤拍  pass 流拍  deal 落锤  re 重拍

            $update = [];
            switch ($_POST["op"]){
                case "start"  : $update = ["state" => 1]; break;
                case "cancel" : $update = ["state" => 0, "final_price" => 0, "clinch_time" => 0, "nid" => 0, "ub_id" => 0, "up_id" => 0, "revoke_bid" => ""]; break;
                case "pass"   : $update = ["state" => 6, "final_price" => 0, "clinch_time" => time(), "nid" => 0, "ub_id" => 0, "up_id" => 0, "revoke_bid" => ""]; break;
                case "deal"   : $update = ["state" => 8, "final_price" => $good1["final_price"] == 0 ? $good1["price"] : $good1["final_price"], "clinch_time" => time()]; break;
                case "re"     : $update = ["state" => 1, "final_price" => 0, "clinch_time" => 0, "nid" => 0, "ub_id" => 0, "up_id" => 0, "revoke_bid" => ""]; break;
            }

            Db::name("goods")->where("gid", $gid)->update($update);
            $good = Db::name("goods")->where("gid", $gid)->find();
            $image = $this->SearchImg($good["lid"], $good["number"]);
            $num = $this->GetPeople($good);

            $next_index = "";
            $goods = Db::name("goods")->where("lid", $good1["lid"])->order("number asc")->select();
            if($_POST["op"] == "pass" || $_POST["op"] == "deal"){
                $a = Db::name("goods")->where("lid", $good1["lid"])->where("gid > {$good1["gid"]}")->where("state", 0)->find();
                if(empty($a)){
                    $b = Db::name("goods")->where("lid", $good1["lid"])->where("gid < {$good1["gid"]}")->where("state", 0)->find();
                    if(!empty($b)){
                        foreach ($goods as  $key=> $val){
                            if($val["gid"] == $b["gid"]){
                                $next_index = $key;
                                break;
                            }
                        }
                    }
                }else{
                    foreach ($goods as  $key=> $val){
                        if($val["gid"] == $a["gid"]){
                            $next_index = $key;
                            break;
                        }
                    }
                }
            }


            $data = [
                "id" => (int)$good["gid"],
                "cover" => $image[0],
                "curr" => $good["state"] == 6 ? "" : $good["final_price"] == 0 ? $good["price"] : $good["final_price"],
                "curr_buyer" => ($good["state"] == 3 || $good["state"] == 4 || $good["state"] == 5) ? ((is_bool($num) && !$num) ? 0 : $num) : "",
                "final" => $this->GetFinal($good),
                "lot" => $good["number"],
                "name" => $good["name"],
                "start" => $good["price"],
                "state" => ($good["state"] == 0 || $good["state"] == 1) ? (int)$good["state"] : 2,
                "next_index" => $next_index
            ];

            # 商品总数 $all_good
            $AllGoodNum = Db::name("goods")
                ->where("lid", $good["lid"])
                ->count();

            # 成交数 $chengjiao
            $ClinchNum = Db::name("goods")
                ->where("lid", $good["lid"])
                ->where(function ($query){
                    $query->where("state", 3)->whereOr("state", 4)->whereOr("state", 5);
                })
                ->count();

            # 流拍数 $liupai
            $PassByNum = Db::name("goods")
                ->where("lid", $good["lid"])
                ->where("state", 6)
                ->count();

            # 没有开始的数量 $no
            $NoStartNum = Db::name("goods")
                ->where("lid", $good["lid"])
                ->where("state", 0)
                ->count();

            # 成功拍卖的价格总数 $all_price
            $AllPrice = Db::name("goods")
                ->where("lid", $good["lid"])
                ->where(function ($query){
                    $query->where("state", 3)->whereOr("state", 4)->whereOr("state", 5);
                })
                ->field("SUM(final_price) as all_price")
                ->find();

            # 近期的三条数据 $goods_limit
            $RecentLimit = Db::name("goods")
                ->where("lid", $good["lid"])
                ->where("state", 3)
                ->order("clinch_time desc")
                ->limit(1)
                ->select();

            $lot = Db::name("lot")->where("lid", $good["lid"])->find();

            $number = $this->GetPeople($good);

            $eval = $this->EvalPrice($good, 2);
            $good_data = [
                "id" => (int)$good["gid"],
                "cover" => $image[0],
                "curr" => $good["final_price"] == 0 ? $good["price"] : $good["final_price"],
                "curr_buyer" => ($good["state"] == 3 || $good["state"] == 4 || $good["state"] == 5) ? ((is_bool($number) && !$number) ? 0 : $number) : "",
                "curr_convert" => $good["final_price"] == 0 ? "￥ ".number_format((float)$good["price"] * (float)$lot["rate"],0) : "￥ ".number_format((float)$good["final_price"] * (float)$lot["rate"], 0),
                "final" => $this->GetFinal($good, false),
                "lot" => $good["number"],
                "name" => $good["name"],
                "start" => (float)$good["price"],
                "start_convert" => "￥ ".number_format((float)$good["price"] * (float)$lot["rate"], 0),
                "start_unit" => "￥",
                "state" => ($good["state"] == 0 || $good["state"] == 1) ? (int)$good["state"] : 2,
                "eval" => $eval,
                "subid" => $lot["aid"]
            ];

            if($_POST["op"] == "pass"){
                $good_data["livePlay"] = ["is_turnon"] == 1;
            }

            $curr_buy = (is_bool($number) && !$number) ? "恭喜现场{$good["peo_num"]}成交！" : (is_numeric($number) ? "恭喜网络: 竞拍号码 [{$number}] 成交！" : "恭喜 {$number} 成交");

            $last_good = Db::name("goods")->where("lid", $good["lid"])->order("clinch_time desc")->find();
            $last = false;
            if(!empty($last_good)){
                $last = [
                    "bid" => $last_good["final_price"] == 0 ? $last_good["price"] : $last_good["final_price"],
                    "lot" => $last_good["number"],
                    "state" => $last_good["state"] == 6 ? "流拍" : "成交"
                ];
            }

            $recent = [];
            if(!empty($RecentLimit)){
                foreach ($RecentLimit as $value){
                    $num = $this->GetPeople($value);

                    $recent = [
                        "buyer_num" => $value["final_price"] == 0 ? "" : (is_bool($num) && !$num) ? $value["peo_num"] : $num,
                        "buyer_way" => $value["final_price"] == 0 ? "" : (is_bool($num) && !$num) ? "现场" : "网络",
                        "final" => $this->GetFinal($value),
                        "lot" => $value["number"],
                    ];
                }
            }

            $send1 = [];
            switch ($_POST["op"]){
                case "start"  : $send1 = ["type" => "startAuc", "lot_id" => $good["lid"], "goods" => $good_data, "msg" => "开始出价！", "last" => $last]; break;
                case "cancel" : $send1 = ["type" => "cancelAuc", "lot_id" => $good["lid"], "goods" => false, "msg" => "抱歉，本件撤拍，等待管理员上架下一件！"]; break;
                case "pass"   : $send1 = ["type" => "passAuc", "lot_id" => $good["lid"], "goods" => $good_data, "recent" => $recent, "msg" => "本件流拍！"]; break;
                case "deal"   : $send1 = ["type" => "dealAuc", "lot_id" => $good["lid"], "goods" => $good_data, "recent" => $recent, "msg" => $curr_buy]; break;
                case "re"     : $send1 = ["type" => "reAuc", "lot_id" => $good["lid"], "goods" => $good_data, "msg" => $msg]; break;
            }

            /* 更新专场统计 */
            $send = [
                "type" => "count",
                "lot_id" => $good["lid"],
                "num" => [$AllGoodNum, $ClinchNum, $PassByNum, $NoStartNum],
                "deal" => [$AllPrice["all_price"] == null ? "0" : $AllPrice["all_price"], round($ClinchNum/$AllGoodNum*100,2)."%"],
            ];

            $this->sendTogrounp($send, $good["lid"]);
            $this->sendTogrounp($send1, $good["lid"]);

            Code(200, false, $data);
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 出价
    public function PostLiveBid(){
        if(isset($_POST["id"]) && isset($_POST["bid"])){
            $gid = $_POST["id"];
            $bid = $_POST["bid"];
            $uid = 0;

            $good = Db::name("goods")->where("gid", $gid)->find();
            $revoke = "";
            if($good["final_price"] != 0){
                $save = [
                    "nid" => $good["nid"],
                    "up_id" => $good["up_id"],
                    "ub_id" => $good["ub_id"],
                    "final_price" => $good["final_price"]
                ];
                $revoke = json_encode($save, 256);
            }

            $update = [
                "final_price" => $bid,
                "nid" => 0,
                "ub_id" => 0,
                "up_id" => 0,
                "revoke_bid" => $revoke
            ];

            Db::name("goods")->where("gid", $gid)->update($update);
            $lot = Db::name("lot")->where("lid", $good["lid"])->find();
            $send = [
                "type" => "bid",
                "lot_id" => $good["lid"],
                "num" => 0,
                "bid" => $bid,
                "convert" => "￥ ".number_format(((float)$bid * (float)$lot["rate"]), 0),
            ];
            $this->sendTogrounp($send, $lot["lid"]);
            Code(200, "出价成功", (Object)[]);
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 设置直播状态
    public function SetLivePush(){
        if(isset($_POST["id"]) && isset($_POST["live"])){
            $lid = $_POST["id"];
            $live = $_POST["live"];

            $update = [
                "is_turnon" => $live
            ];
            Db::name("lot")->where("lid", $lid)->update($update);

            $LiveUrl = "";
            $LiveQr = "";
            if($live == 1){
                $LiveUrl = $this->getPushUrl("lot".$lid, date("Y-m-d H:i:s", time() + 3600*72));
                QRcode::png($LiveUrl, "./static/upload/liveQr/".$lid.".jpg", "L", 6, 1);
                $LiveQr = Config::get("app.ip")."static/upload/liveQr/{$lid}.jpg?t=".time();
            }

            $array = [
                "play" => $_POST["live"] == 1,
                "url" => $LiveUrl,
                "qr" => $LiveQr
            ];

            $send = [
                "type" => "livePlay",
                "lot_id" => $lid,
                "play" => $live == 1,
                "url" => $LiveUrl,
                "qr" => $LiveQr
            ];
            $this->sendTogrounp($send, $_POST["id"]);

            Code(200, false, $array);
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 恢复到上一个人出价
    public function RevokeBid(){
        if(isset($_POST["id"])){
            $gid = $_POST["id"];
            $good = Db::name("goods")->where("gid", $gid)->find();
            if($good["revoke_bid"] == ""){
                $update = [
                    "final_price" => 0,
                    "nid" => 0,
                    "ub_id" => 0,
                    "up_id" => 0,
                    "revoke_bid" => ""
                ];
            }else{
                $revoke = json_decode($good["revoke_bid"], true);
                $update = [
                    "final_price" => $revoke["final_price"],
                    "nid" => $revoke["nid"],
                    "ub_id" => $revoke["ub_id"],
                    "up_id" => $revoke["up_id"],
                    "revoke_bid" => ""
                ];
            }
            Db::name("goods")->where("gid", $gid)->update($update);
            $new_good = Db::name("goods")->where("gid", $gid)->find();
            $lot = Db::name("lot")->where("lid", $new_good["lid"])->find();

            $num = $this->GetPeople($new_good);

            $send = [
                "type" => "revoke",
                "lot_id" => $new_good["lid"],
                "num" => $new_good["final_price"] == 0 ? "" : (is_bool($num) && !$num) ? $new_good["peo_num"] : $num,
                "bid" => $new_good["final_price"] == 0 ? $new_good["price"] : $new_good["final_price"],
                "convert" => "￥ ".number_format((($new_good["final_price"] == 0 ? (float)$new_good["price"] : (float)$new_good["final_price"]) * $lot["rate"]), 0),
            ];
            $this->sendTogrounp($send, $new_good["lid"]);
            Code(200, "撤回成功");
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 设置现场成交号码牌
    public function SetLiveNum(){
        if(isset($_POST["lotId"]) && isset($_POST["goodsId"]) && isset($_POST["liveNum"])){
            $livenum =  $_POST["liveNum"];
            $gid = $_POST["goodsId"];
            $lid = $_POST["lotId"];
            $lot = Db::name("lot")->where("lid", $lid)->find();
            $num = Db::name("num")->where("aid", $lot["aid"])->where("number", $livenum)->find();
            if(empty($num) || $num["ub_id"] == 0){
                Code(403, "对不起号码不存在或者未绑定");
            }else{
                $update = [
                    "nid" => $num["nid"],
                    "ub_id" => $num["ub_id"],
                    "up_id" => 0,
                    "peo_num" => ""
                ];
                Db::name("goods")->where("gid", $gid)->update($update);
                Code(200, false, (Object)[]);
            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function GetScreenData(){
        $aid = $this->token["id"];
        if(isset($_GET["id"])){
            $lid = $_GET["id"];
            $lot = Db::name("lot")->where("aid", $aid)->where("lid", $lid)->find();
            if(!empty($lot)){
                # 获取正在进行的拍品 $good
                $NowGood = Db::name("goods")
                    ->where("lid", $lid)
                    ->where("state", 1)
                    ->find();

                # 获取全部拍品数量 $goods_all
                $AllGood = Db::name("goods")
                    ->where("lid", $lid)
                    ->count();

                # 获取获拍总数 $goods_su
                $GetGoodNum = Db::name("goods")
                    ->where("lid", $lid)
                    ->where(function ($query){
                        $query->where("state", 3)->whereOr("state", 4)->whereOr("state", 5);
                    })
                    ->count();

                # 流拍总数 $goods_liu
                $PassByNum = Db::name("goods")
                    ->where("lid", $lid)
                    ->where("state", 6)
                    ->count();

                # 未开拍总数 $goods_no
                $NoStartNum = Db::name("goods")
                    ->where("lid", $lid)
                    ->where("state", 0)
                    ->count();
                # 最近成交的记录 $last_good
                $LastGood = Db::name("goods")
                    ->where("lid", $lid)
                    ->order("clinch_time desc")
                    ->find();
                $curr = false;
                $bids = [];
                if(!empty($NowGood)){
                    $number = $this->GetPeople($NowGood);
                    if($NowGood["final_price"] != 0){
                        $bids[] = [
                            "num" => (is_bool($number) && !$number) ? 0 : $number,
                            "way" => (is_bool($number) && !$number) ? "现场" : "网络",
                            "bid" => (float)$NowGood["final_price"]
                        ];
                    }

                    if($NowGood["revoke_bid"] != ""){
                        $revoke = json_decode($NowGood["revoke_bid"], true);
                        $revoke_num = $this->GetPeople($revoke);
                        $bids[] = [
                            "num" => (is_bool($revoke_num) && !$revoke_num) ? 0 : $number,
                            "way" => (is_bool($revoke_num) && !$revoke_num) ? "现场" : "网络",
                            "bid" => $revoke["final_price"]
                        ];
                    }

                    $image = $this->SearchImg($NowGood["lid"], $NowGood["number"]);
                    $curr = [
                        "id" => $NowGood["gid"],
                        "lot" => $NowGood["number"],
                        "name" => $NowGood["name"],
                        "curr" => $NowGood["final_price"] == 0 ? (float)$NowGood["price"] : (float)$NowGood["final_price"],
                        "cover" => $image[0],
                        "spec" => $this->Spec($NowGood, $this->spec),
                        "start" => $NowGood["price"],
                        "resr_price" => $NowGood["resr_price"]
                    ];
                }

                $last = false;
                if(!empty($LastGood)){
                    $last = [
                        "bid" => $LastGood["final_price"] == 0 ? $LastGood["price"] : $LastGood["final_price"],
                        "lot" => $LastGood["number"],
                        "state" => $LastGood["state"] == 6 ? "流拍" : "成交"
                    ];
                }

                $h5Url = Config::get("app.ip")."mobile/#/pages/aucing/chat?id={$lid}";
                QRcode::png($h5Url, "./static/upload/liveQr/{$lid}.jpg", "L", 6, 1);
                $h5Qr = Config::get("app.ip")."static/upload/liveQr/{$lid}.jpg?t=".time();

                $array = [
                    "bids" => $bids,
                    "curr" => $curr,
                    "name" => $lot["name"],
                    "num" => [$AllGood, $GetGoodNum, $PassByNum, $NoStartNum],
                    "last" => $last,
                    "h5Qr" => $h5Qr
                ];

                Code(200, false, $array);
            }else{
                Code(403, "专场不存在");
            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 获取价格进度
    public function GetCtrlCurr(){
        (new \app\bidco\controller\Aucing())->GetBidcoCurr();
    }

    public function PassNetBid(){
        if(isset($_POST["num"]) && isset($_POST["bid"]) && isset($_POST["type"]) && isset($_POST["buyer_way"]) && isset($_POST["id"])){
            $num = $_POST["num"];
            $bid = $_POST["bid"];
            $type = $_POST["type"];
            $gid = $_POST["id"];

            $good = Db::name("goods")->where("gid", $gid)->find();
            $lot = Db::name("lot")->where("lid", $good["lid"])->find();
            if($good["state"] == 1){
                if(($good["final_price"] == 0 && $bid >= $good["price"]) || ($good["final_price"] !=0 && $bid > $good["final_price"])){

                    $revoke = "";
                    if($good["final_price"] != 0){
                        $save = [
                            "nid" => $good["nid"],
                            "up_id" => $good["up_id"],
                            "ub_id" => $good["ub_id"],
                            "final_price" => $good["final_price"]
                        ];
                        $revoke = json_encode($save, 256);
                    }

                    $nid = 0;
                    $uid = 0;
                    $aid = 0;
                    if(is_numeric($num)){
                        $number = Db::name("num")
                            ->where("aid", $lot["aid"])
                            ->where("number", $num)
                            ->find();
                        $nid = $number["nid"];
                        $uid = $number["ub_id"];
                    }else{
                        $proxy = Db::name("user_proxy")->where("name", $num)->find();
                        $aid = $proxy["up_id"];
                    }
                    $update = [
                        "final_price" => $bid,
                        "nid" => $nid,
                        "ub_id" => $uid,
                        "up_id" => $aid,
                        "revoke_bid" => $revoke
                    ];
                    Db::name("goods")->where("gid", $gid)->update($update);

                    $send = [
                        "type" => "bid",
                        "lot_id" => $good["lid"],
                        "num" => $num,
                        "bid" => $bid,
                        "convert" => "￥ ".number_format(((float)$bid * (float)$lot["rate"]), 0),
                    ];
                    $this->sendTogrounp($send, $lot["lid"]);
                    Code(200, false, (Object)[]);
                }else{
                        Code(403, "出价必须高于当前价");
                }
            }else{
                Code(403, "该拍品未在进行中");
            }
        }else{
            Code(403, "服务器错误，请稍后再试");
        }
    }

}
